package al.work.common.util;

import java.util.HashMap;
import java.util.Map;

/**
 * @author JiuZh
 */
public class ContextHolder {

    private static SelfThreadLocal<Map<String,Object>> threadLocal = new SelfThreadLocal<>(() -> new HashMap<>());

    /**
     * 不能实例化
     */
    private ContextHolder() {}

    /**
     * 获取数据
     * @param key
     * @param <T>
     * @return
     */
    public static <T> T get(String key) {
        if (null == key) {
            throw new IllegalArgumentException("key cannot be null");
        }
        Object result = threadLocal.local().get(key);
        return (T)result;
    }

    /**
     * 插入数据
     * @param key
     * @param vl
     * @param <T>
     */
    public static <T> void put(String key, T vl) {
        if (null == key) {
            throw new IllegalArgumentException("key cannot be null");
        }
        if (null == vl) {
            threadLocal.local().remove(key);
        } else {
            threadLocal.local().put(key, vl);
        }
    }

    /**
     * 移除
     * @param key
     */
    public static void remove(String key) {
        if (null == key) {
            throw new IllegalArgumentException("key cannot be null");
        }
        threadLocal.local().remove(key);
    }

    /**
     * 清空
     */
    public static void clear() {
        threadLocal.local().clear();
    }
}
